package tchk.xyz.lingyuntutorminiprogram.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import tchk.xyz.lingyuntutorminiprogram.entity.SysUser;
import tchk.xyz.lingyuntutorminiprogram.mapper.SysPermissionMapper;
import tchk.xyz.lingyuntutorminiprogram.service.IUserService;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;

    @Autowired
    private SysPermissionMapper sysPermissionMapper; // 注入我们刚写的Mapper

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 根据用户名从数据库查询用户
        SysUser sysUser = userService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username));

        // 2. 如果用户不存在，抛出异常
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        // 3. [核心修改] 查询该用户的权限信息
        List<String> permissionCodes = sysPermissionMapper.findPermissionCodesByUserId(sysUser.getId());

        // 4. 将权限标识符字符串列表，转换为Spring Security需要的GrantedAuthority对象列表
        List<GrantedAuthority> authorities = permissionCodes.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());

        // 5. 将用户信息封装成Spring Security的UserDetails对象并返回
        return new User(
                sysUser.getUsername(),
                sysUser.getPassword(),
                authorities // <- 传入真实的权限集合
        );
    }
}